package com.kuzan.autocloud.gateway.filter;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.kuzan.autocloud.gateway.JWTValid;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;

import static com.kuzan.autocloud.common.Constant.AuthorizationOrganization;
import static com.kuzan.autocloud.common.Constant.AuthorizationPerson;

/**
 * <p>Description: </p>
 *
 * @author kuzank
 */
@Component
public class AuthFilter extends JWTValid implements GlobalFilter, Ordered {

    @Value("${auth.skip.urls}")
    private String[] skipAuthUrls;
    @Value("${jwt.blacklist.key.format}")
    private String jwtBlacklistKeyFormat;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public int getOrder() {
        return -100;
    }


    /**
     * 外部 Api 请求系统后，经由网关服务过滤，将 HttpRequest token 解析为 person & organization，
     * 并保存在 HttpRequest 以供系统内部使用中
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        String url = exchange.getRequest().getURI().getPath();
        log.info(url);

        // 从请求头中取出token
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        DecodedJWT data = null;
        try {
            if (StringUtils.isNotEmpty(token)) {
                // 取出token包含的身份
                token = token.replace("Bearer ", "");
                data = verifyJWT(token);
            }
        } catch (Exception ex) {
            return ValidErrorResult(exchange, 301);
        }

        String orgunit = null, person = null;
        if (data != null) {
            orgunit = data.getClaim("orgunit").asString();
            person = data.getClaim("person").asString();
        }

        // 将现在的request，添加当前身份
        ServerHttpRequest mutableReq = exchange.getRequest().mutate()
                .header(AuthorizationOrganization, orgunit)
                .header(AuthorizationPerson, person)
                .build();

        ServerWebExchange mutableExchange = exchange.mutate().request(mutableReq).build();

        // 跳过不需要验证的路径
        String urlPath = url.replaceAll("/[0-9a-z]{8}[0-9a-z]{4}[0-9a-z]{4}[0-9a-z]{4}[0-9a-z]{12}", "");
        if (Arrays.asList(skipAuthUrls).contains(urlPath)) {
            return chain.filter(mutableExchange);
        }

        // 未携带token或token在黑名单内
        if (token == null || token.isEmpty() || isBlackToken(token)) {
            return ValidErrorResult(mutableExchange, 301);
        }

        if (person.isEmpty()) {
            return ValidErrorResult(mutableExchange, 301);
        }

        return chain.filter(mutableExchange);
    }


    /**
     * 判断token是否在黑名单内
     *
     * @param token
     * @return
     */
    private boolean isBlackToken(String token) {
        assert token != null;
        return stringRedisTemplate.hasKey(String.format(jwtBlacklistKeyFormat, token));
    }
}
